package byggeTegning.geometry;

//import DEBUGGING.*;  // Search for DEBUG.<INFO|TRACE| ... >

import javax.media.j3d.*;
import javax.vecmath.*;

// ********************************************************************
// *** CLASS: Polygon
// ********************************************************************
public class Polygon extends Shape3D
{
  private static final int vertexFormat
          = GeometryArray.COORDINATES
          | GeometryArray.NORMALS
          | GeometryArray.TEXTURE_COORDINATE_2;
  
  private static final Point2f texCoord[] // SKAL RETTES OPP SENERE
          = { new Point2f(0.0f, 0.0f),
              new Point2f(0.5f, 0.0f),
              new Point2f(0.5f, 0.5f),
            };
    

  // ******************************************************************
  // *** CONSTRUCTOR: Polygon
  // ******************************************************************
  /**
  * @param p polygon. Forside: punktene nevnes 'mot klokka'
  */
  public Polygon(Point3f[] p)
  { int i,face;
    int nFace=p.length-1;
    int N=nFace*3;
//    ASSERT(p[0].equals(p[nFace]));
    
    Point3f[] verts=new Point3f[N]; // triangles
    Point3f pc=center(p);
    int j=0;
    for(i=1;i<=nFace;i++)
    {
//      DEBUG.INFO("TEST! N="+N+", nFace="+nFace+", i="+i+", j="+j);
      verts[j++]=p[i];
      verts[j++]=pc;
      verts[j++]=p[i-1];
    }
    TriangleArray tetra=new TriangleArray(N,vertexFormat);
    tetra.setCoordinates(0,verts);

    for(i=0;i<N;i++) tetra.setTextureCoordinate(i,texCoord[i%3]);

    Vector3f normal=new Vector3f();
    Vector3f v1=new Vector3f();
    Vector3f v2=new Vector3f();
    Point3f[] pts=new Point3f[3];
    for(i=0;i<3;i++) pts[i]=new Point3f();
    for(face=0;face<nFace;face++)
    { tetra.getCoordinates(face*3,pts);
      v1.sub(pts[1],pts[0]);
      v2.sub(pts[2],pts[0]);
      normal.cross(v1,v2);
      normal.normalize();
      for(i=0;i<3;i++) tetra.setNormal((face*3 + i),normal);
    }
    this.setGeometry(tetra);
    this.setAppearance(new Appearance());
  }
  
  // ******************************************************************
  // *** UTILITY: center
  // ******************************************************************
  private Point3f center(Point3f[] p)
  { float x=0,y=0,z=0; int n=p.length;
    for(int i=0;i<n;i++)
    { x+=p[i].x; y+=p[i].y; z+=p[i].z; }  
    return(new Point3f(x/n,y/n,z/n));
  }  
  
}